package com.alu4r.atcrowdfunding.manager.controller;

import com.alu4r.atcrowdfunding.bean.Permission;
import com.alu4r.atcrowdfunding.manager.service.PermissionService;
import com.alu4r.atcrowdfunding.util.JsonMessageResult;
import com.alu4r.atcrowdfunding.util.PermissionTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    PermissionService permissionService;



    @ResponseBody
    @RequestMapping("/deletePermission")
    public JsonMessageResult deletePermission(Integer id){
        System.out.println("删除许可");
        JsonMessageResult jsonMessageResult;
        boolean isSuccess = permissionService.deletePermission(id);
        if (isSuccess) {
            jsonMessageResult = JsonMessageResult.success();
        }else {
            jsonMessageResult = JsonMessageResult.success();
        }

        return jsonMessageResult;
    }

    @ResponseBody
    @RequestMapping("/doEdit")
    public JsonMessageResult doEdit(Permission permission){
        System.out.println("跳转到许可维护模块");
        System.out.println("edit"+permission.getName());
        JsonMessageResult jsonMessageResult;
        boolean isSuccess = permissionService.updatePermission(permission);
        if (isSuccess) {
            jsonMessageResult = JsonMessageResult.success();
        }else {
            jsonMessageResult = JsonMessageResult.success();
        }

        return jsonMessageResult;
    }

    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonMessageResult doAdd(Permission permission){
        System.out.println("跳转到许可维护模块");
        JsonMessageResult jsonMessageResult;
        boolean isSuccess = permissionService.insertPermission(permission);
        if (isSuccess) {
            jsonMessageResult = JsonMessageResult.success();
        }else {
            jsonMessageResult = JsonMessageResult.success();
        }

        return jsonMessageResult;
    }

    @ResponseBody
    @RequestMapping(value = "/getTree", method = RequestMethod.POST)
    public JsonMessageResult getTree() {
        JsonMessageResult jsonMessageResult;


        List<Permission> allPermission = null;
        try {
            allPermission = permissionService.queryAllPermission();
            jsonMessageResult = JsonMessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            jsonMessageResult = JsonMessageResult.fail();
        }
        List<Permission> root = PermissionTree.getTree(allPermission);


        return jsonMessageResult.add("zNodes", root);
    }
}
